<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>实时轨迹</title>
    <script>
        window.addEventListener("beforeunload", function() {
            clearTrack();
        });

        // 全局初始化回调
        function initBaiduMap() {
            window.BMap = BMap;  // 暴露到全局对象
            initMap();  // 执行地图初始化
        }

        // 异步加载地图API
        (function() {
            var script = document.createElement('script');
            script.src = 'https://api.map.baidu.com/api?v=3.0&ak=by0bKenzQDm5womuoAxsl1hfgyUAeM0s&callback=initBaiduMap';
            script.async = true;
            document.head.appendChild(script);
        })();

        window.initMap = function() {
            console.log("开始初始化地图");
            map = new BMap.Map("container");
            map.centerAndZoom(new BMap.Point(114.06, 22.54), 15);
            map.enableScrollWheelZoom(true);
            map.addControl(new BMap.NavigationControl());
            console.log("地图初始化完成");

            // 设置 mapLoaded 为 true
            window.mapLoaded = true;
        };

        window.drawNewPoint = function(lng, lat) {
            console.log("收到新坐标:", lng, lat);

            // 保留最近50个点（可根据需要调整）
            if (!window.points) window.points = [];
            points.push(new BMap.Point(lng, lat));
            if (points.length > 50) points.shift();

            // 更新轨迹线
            if (window.polyline) {
                try {
                    map.removeOverlay(window.polyline);
                } catch (e) {
                    console.error("移除旧轨迹失败:", e);
                }
            }

            try {
                window.polyline = new BMap.Polyline(points, {
                    strokeColor: "#00FF00",
                    strokeWeight: 4,
                    strokeOpacity: 0.8
                });
                map.addOverlay(window.polyline);
                map.panTo(points[points.length - 1]);
            } catch (e) {
                console.error("绘制轨迹失败:", e);
            }
        };
        //清除轨迹的方法
        window.clearTrack = function() {
            if (window.polyline) {
                try {
                    map.removeOverlay(window.polyline);
                } catch (e) {
                    console.error("清除轨迹失败:", e);
                }
            }
            points = [];  // 重置轨迹点
            polyline = null;
        };
    </script>
</head>
<body>
<div id="container" style="width:480px;height:854px;"></div>
</body>
</html>
